package com.lzc.tlmail.tlmailproduct.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lzc.tlmail.tlmailproduct.dao.CategoryBrandRelationDao;
import com.lzc.tlmail.tlmailproduct.entity.CategoryBrandRelationEntity;
import com.lzc.tlmail.tlmailproduct.service.CategoryBrandRelationService;
import com.lzc.tlmail.tlmailproduct.vo.Level2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzc.common.utils.PageUtils;
import com.lzc.common.utils.Query;

import com.lzc.tlmail.tlmailproduct.dao.CategoryDao;
import com.lzc.tlmail.tlmailproduct.entity.CategoryEntity;
import com.lzc.tlmail.tlmailproduct.service.CategoryService;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.lang.model.type.ReferenceType;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取所有分类
     *
     * @return
     */
    @Override
    public List<CategoryEntity> queryAllListWithTree() {
        //1获得所有种类
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
        //2找到所有一级分类
        List<CategoryEntity> collect = categoryEntityList.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(menu -> {
                    //调用子菜单递归操作
                    menu.setChilds(getChilds(menu, categoryEntityList));
                    return menu;
                })
                .collect(Collectors.toList());
        return collect;
    }

    /**
     * 批量删除方法
     *
     * @param asList
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1 检查当前删除的菜单 是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 根据id得到所有节点id
     *
     * @param id
     * @return
     */
    @Override
    public Long[] getPathsById(Long id) {
        List<Long> paths = new ArrayList<>();
        List<Long> paths1 = findPaths(id, paths);
        Collections.reverse(paths1);
        return paths1.toArray(new Long[paths1.size()]);
    }

    /**
     * 修改分类信息
     * @param category
     */
    @Override
    @CacheEvict(value = "category",allEntries = true)
    public void updateDetailsById(CategoryEntity category) {
        //修改分类
        if (category != null) {
            this.categoryDao.updateById(category);
            if (!StringUtils.isEmpty(category.getName())) {
                categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
            }

        }

    }

    /**
     * 获取一级分类
     *
     * @return
     */
    @Cacheable(value = "category",key = "'queryLevel1Category'",sync = true)
    @Override
    public List<CategoryEntity> queryLevel1Category() {
        List<CategoryEntity> categoryEntities = categoryDao.selectList(new LambdaQueryWrapper<CategoryEntity>()
                .eq(CategoryEntity::getCatLevel, 1));
        return categoryEntities;
    }


    /**
     * 获取所有二级分类和他的三级分类信息 加上分布式锁
     * 键是1级分类 值是对应的下面的分类信息
     *
     * @return
     */
    @Cacheable(value = "category",key = "'getLevel2Category'",sync = true)
    @Override
    public Map<String, List<Level2Vo>> getLevel2Category() {
        RLock lock = redissonClient.getLock("CategoryJson-lock");
        lock.lock();
        Map<String, List<Level2Vo>> forRedis=null;
        try {
            forRedis= getLevel2CategoryForDB();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        return forRedis;
    }




    /**
     * 从缓存中查找分类
     * @return
     */
    public Map<String, List<Level2Vo>> getLevel2CategoryForDB() {
        //获取所有分裂
        List<CategoryEntity> categoryEntities = categoryDao.selectList(null);
        //获取一级分类
        List<CategoryEntity> level1Category = getCategoryEntityList(categoryEntities,0L);
        Map<String, List<Level2Vo>> collect = level1Category.stream().collect(Collectors.toMap(ll1 -> ll1.getCatId().toString(),
                item1 -> {
                    //得到二级分类
                    List<CategoryEntity> level2 = getCategoryEntityList(categoryEntities,item1.getCatId());
                    List<Level2Vo> level2Vos = null;
                    if (level2 != null) {
                        level2Vos = level2.stream().map(l2 -> {
                            Level2Vo level2Vo = new Level2Vo(item1.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                            //得到三级分类
                            List<CategoryEntity> level3 = getCategoryEntityList(categoryEntities,l2.getCatId());
                            List<Level2Vo.Leve13Vo> leve13Vos = level3.stream().map(l3 -> {
                                Level2Vo.Leve13Vo leve13Vo = new Level2Vo.Leve13Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                return leve13Vo;
                            }).collect(Collectors.toList());
                            level2Vo.setCatalog3List(leve13Vos);
                            return level2Vo;
                        }).collect(Collectors.toList());
                    }
                    return level2Vos;
                }));

        return collect;
    }

    /**
     * 根据分类id获取分类列表
     * @param categoryEntities
     * @param catId
     * @return
     */
    private List<CategoryEntity> getCategoryEntityList(List<CategoryEntity> categoryEntities,Long catId ) {
        return categoryEntities.stream().filter(item->item.getParentCid().equals(catId)).collect(Collectors.toList());
    }


    /**
     * 递归方法获取所有分类id
     */

    private List<Long> findPaths(Long id, List<Long> paths) {
        paths.add(id);
        CategoryEntity byId = this.getById(id);
        if (byId.getParentCid() != 0) {
            findPaths(byId.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 获取子菜单递归操作
     */
    public List<CategoryEntity> getChilds(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> childs = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .map(categoryEntity -> {
                    //找到子菜单
                    categoryEntity.setChilds(getChilds(categoryEntity, all));
                    return categoryEntity;
                })
                //排序
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());
        return childs;
    }

}